<template>
  <!-- 注册页面 -->
  <el-main>
    <div style="text-align: center;font-size:24px;color:rgb(96,98,102) ;margin-top: 100px;">
      <span v-if="registInfo.merchantView">汤臣一品便民服务中心 - 商户注册</span>
      <span v-else>汤臣一品便民服务中心 - 用户注册</span>
    </div>
    <el-row style="margin-top: 60px;margin-bottom: 100px;">
      <el-col :span="10" :offset="6">
        <el-form :model="registInfo" status-icon :rules="rules" ref="registInfo" label-width="100px" class="demo-ruleForm">
          <el-form-item label="昵称" prop="user.name">
            <el-input v-model="registInfo.user.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="user.username">
            <el-input v-model="registInfo.user.username" @blur="checkUsername()" clearable></el-input><h2 v-if="samename" style="color: red;text-align: left;">用户名不可用</h2>
          </el-form-item>
          <el-form-item label="密码" prop="user.password">
            <el-input type="password" v-model="registInfo.user.password" autocomplete="off" clearable></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="user.phone">
            <el-input v-model.number="registInfo.user.phone" clearable></el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input v-model.number="registInfo.code" style="width:180px;" clearable></el-input>
            <el-button round @click="sendCode()" style="margin-left: 15px;">
              <span v-if="codeDisable">重新发送({{timeout}}s)</span>
              <span v-else>发送验证码</span>
            </el-button>
          </el-form-item>
          <!-- <span v-if="registInfo.merchantView">
            <el-form-item label="商户名称" prop="merchant.name">
              <el-input v-model="registInfo.merchant.name" clearable></el-input>
            </el-form-item>
            <el-form-item label="商户介绍" prop="merchant.detail">
              <el-input v-model="registInfo.merchant.detail" clearable></el-input>
            </el-form-item>
            <el-form-item label="营业执照" prop="merchant.charter">
              <el-upload
                name="files"
                class="upload-demo"
                action="http://localhost:8080/oos/upload/img/charter"
                :on-success="handleSuccess"
                :on-remove="handleRemove"
                :limit="1"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1mb</div>
              </el-upload>
            </el-form-item>
          </span> -->
          <el-form-item>
            <el-button type="primary" @click="regist()">用户注册</el-button>
            <el-button type="primary" @click="regist1();regist()">商家注册</el-button>
            <!-- <el-button v-if="!registInfo.merchantView" type="info" @click="registInfo.merchantView = true;">成为商家</el-button>
            <el-button v-else type="info" @click="registInfo.merchantView = false;">返回</el-button> -->
          </el-form-item>
        </el-form>

      </el-col>
    </el-row>
  </el-main>
</template>

<script>
  export default {
    data() {
      return {
        samename:false,
        /* 注册信息，一同传给后端 */
        registInfo: {
          user: {
            name: "",
            username: "",
            password: "",
            phone: "",
            business:false,
            status:1
          },
          // merchant: {
          //   name: "",
          //   detail: "",
          //   charter: "",
          // },
          merchantView: false, // 是否显示商家视图
          code: "",
        },
        /* 禁止频繁发送验证码的倒计时 */
        timeout: 120,
        /* 禁止频繁发送验证码的标记 */
        codeDisable: false,
        rules: {
          "user.name": [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          "user.username": [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          "user.password": [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          "user.phone": [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { type: 'number', message: '电话只能由数字组成'}
          ],
          "merchant.name": [
            { required: true, message: '请输入商户名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          "merchant.detail": [
            { required: true, message: '请输入商户介绍', trigger: 'blur' },
            { min: 10, max: 50, message: '长度在 10 到 50 个字符', trigger: 'blur' }
          ],
          "merchant.charter": [
            { required: true, message: '请上传营业执照', trigger: 'blur' },
          ],
          "code": [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { type: 'number', message: '验证码只能由数字组成'}
          ]
        }
      }
    },
    methods: {

      checkUsername: function(){
        if(this.registInfo.user.username != "" && this.registInfo.user.username.length >= 3 && this.registInfo.user.username.length <=10){
          //查找username是否重名
              this.$axios.get("http://localhost:8080/sysuser/checkUsername/" + this.registInfo.user.username).then(res => {
                if(res.data.code == 200){
                  this.$message.success("该用户名可用")
                  this.samename=false
                }else{
                  this.$message.error("该用户名不可用")
                  this.samename=true
                }
              })
        }

        // if(this.registInfo.user.username != "" && this.registInfo.user.username.length >= 3 && this.registInfo.user.username.length <=10){
        //   this.$axios.get("http://localhost:8080/acct/checkUsername/" + this.registInfo.user.username).then(res => {
        //     if(res.data.status == "SUCCESS"){
        //       this.$message.success("该用户名可用")
        //     }else{
        //       this.$message.error("该用户名不可用")
        //     }
        //   })
        // }
        //alert()
      },
      regist1(){
        this.registInfo.user.business = true
        //console.log(this.registInfo.user.business)
      },
      regist: function(){
        console.log(this.registInfo.user.business)
        //使用element ui自带的验证规则，如果未通过，返回不执行
        let flag = true;
        this.$refs['registInfo'].validate((valid) => {
          if (!valid) {
            flag = false;
          }
        });
        if(!flag){
          this.registInfo.user.business = false
          return;
        }
        if(this.samename==true){
          this.$message.error("用户名不可用")
          this.registInfo.user.business = false
          return;
        }
        /* 手机号格式检查 */
        if(this.registInfo.user.phone.toString().length != 11){
          this.$message.error("请检查手机号格式后重试")
          this.registInfo.user.business = false
          return;
        }

        /* 先检查验证码是否正确，如果正确再发起注册请求 */
        if(this.registInfo.code!=this.code){
          this.$message.error("验证码错误")
          this.registInfo.user.business = false
          return;
        }
        //     /* 验证码正确，继续执行注册 */
          this.$axios.post("http://localhost:8080/sysuser/regist",this.registInfo.user).then(res=>{
            //注册成功
            if(res.data.code==200){
                          this.$router.push("/login")
                          this.$message.success("注册成功")
            }else{
                      this.$message.error("注册失败")
                      this.registInfo.user.business = false
            }
          })
        // this.$axios.get("http://localhost:8080/MSG/verify/" + this.registInfo.user.phone + "/" + this.registInfo.code)
        // .then(res => {
        //   if(res.data.status == "SUCCESS"){
        //     /* 验证码正确，继续执行注册 */
        //     this.$axios.post("http://localhost:8080/acct/regist", this.registInfo).then(res => {
        //       if(res.data.status == "SUCCESS"){
        //         if(this.merchantView){
        //           //注册的是商户，返回到首页
        //           this.$router.push("/")
        //           this.$message.success("注册成功，等待管理员审核通过后即可登录")
        //         }else{
        //           // 客户注册的是用户，返回到登录页面
        //           this.$router.push("/login")
        //           this.$message.success("注册成功")
        //         }
        //       }else{
        //         /* 用户注册失败 */
        //         this.$message.error("注册失败")
        //       }
        //     })

        //   }else{
        //     /* 验证码错误 */
        //     this.$message.error("验证码错误，请检查后重试")
        //   }
        // })
        this.registInfo.user.business = false


      },
      sendCode: function(){
        /* 如果禁止频繁发送验证码标记为true */
        if(this.codeDisable){
          this.$message.error("请勿频繁发送验证码")
          return;
        }

        /* 手机号格式检查 */
        if(this.registInfo.user.phone.toString().charAt(0) != "1"||this.registInfo.user.phone.toString().length != 11){
          this.$message.error("请检查手机号格式后重试")
          return;
        }

        /* 发送验证码 */
        this.$axios.post("http://localhost:8080/sms" , {
         "phoneNumber":this.registInfo.user.phone
        }).then(res => {
          //console.log(res)
          /* 发送成功提示 */
          if(res.data.code == 200){
              this.code = res.data.data;
              //console.log(res)
              this.$message.success("验证码已发送，2分钟内有效")
          }else{
            this.$message.error("验证码发送失败")
          }
          //将验证码放到data

        })

        /* 将禁止频繁发送验证码标记为true */
        this.codeDisable = true;

        /* 设置周期事件，每1000ms减少timeout一秒，周期结束重置验证码发送状态 */
        let interval = setInterval(() => {
          this.timeout --;

          if(this.timeout <= 0){
            window.clearInterval(interval);
            this.codeDisable = false;
            this.timeout = 120;
            this.registInfo.code="";
          }
        }, 1000);
      },
      handleRemove: function(){
        this.registInfo.merchant.charter = ""
      },
      handleSuccess: function(response){
        if(response.status == "SUCCESS"){
          /* 营业执照只能上传一张，只需要把返回数组的0索引赋值给商家营业执照信息 */
          this.$message.success("营业执照上传成功")
          this.registInfo.merchant.charter = response.data[0];
        }else{
          this.$message.error("文件上传失败，请重试")
        }
      }
    },
    mounted() {
      /* 设置页面标题 */
      document.title="注册 - 汤臣一品便民服务中心"
    }
  }
</script>

<style scoped>

</style>
